// 根据指定过期时间自动清除归档日志目录中的数据，过期时间单位为天。

package mylog

import (
	"fmt"
	"time"

	gfile "github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/os/gtime"
)

const (
	AUTO_CHECK_INTERVAL = 3600 // (秒)自动检测时间间隔
)

var LogExpire = 30

func CleanLog() {
	time.Sleep(time.Second)
	go func() {
		for {
			cleanExpiredBackupFiles()
			time.Sleep(AUTO_CHECK_INTERVAL * time.Second)
		}
	}()
}

func SetLogExpire(expire int) {
	LogExpire = expire
}

// 清除过期的备份日志文件
func cleanExpiredBackupFiles() {
	fmt.Println("clear log")
	if list, err := gfile.ScanDir(LogPath, "*.log", true); err == nil {
		for _, path := range list {
			if gfile.IsFile(path) && gtime.Timestamp()-gfile.MTime(path).Unix() >= int64(LogExpire*86400) {
				if err := gfile.Remove(path); err != nil {
					Error(err)
				} else {
					Debug("removed file:", path)
				}
			}
		}
	} else {
		Error(err)
	}
}
